import Wx, {wx} from "./Wx";

/**
 * 创建微信视频广告组件.
 * 视频广告更换周期应当尽可能的长.否则过度消耗用户流量.
 */
export default class VideoAdsProvider {

    private banner: any = null;
    private bannerCreateTime: number = 0;
    // 最小广告创建间隔. 为负值表示每次都创建.
    private minCreateTimeSpan: number = 1 * 60 * 1000;

    // private isShowing: boolean = false;

    // private isPreloading: boolean = false;

    private closeCallback: (finish: boolean) => void = null;

    private adUnitId: string = "";

    private hasError: boolean = false;

    private onVideoLoad = function (ret) {
        cc.log("视频加载成功");
        this.hasError = false
    }.bind(this);

    private onVideoClose = function (res) {
        cc.log("视频广告关闭", res);
        // this.isShowing = false;
        this.isPreloading = false;
        // 通知外界视频是否关闭了.
        if (this.closeCallback) {
            this.closeCallback(res.isEnded);
        }
        this.preloadAds();
    }.bind(this);

    private onError = function (ret) {
        console.error("视频广告加载失败.");
        this.hasError = true;
        this.isShowing = false;
        this.isPreloading = false;
        if (this.closeCallback) {
            this.closeCallback(false);
            this.closeCallback = null;
        }
    }.bind(this);

    // 使用前需要初始化设置adUnitId.
    public setAdId(adId: string) {
        this.adUnitId = adId;
    }

    public isDisabled(): boolean {
        return this.hasError;
    }

    /**
     * banner 更换频率.设置越高,可能越消耗用户流量.
     * @param {number} span
     */
    public setMinCreateSpan(span: number) {
        this.minCreateTimeSpan = span < 0 ? 0 : span;
    }

    // 视频播放完成被关闭的回调设置.
    public setOnCloseListener(callback: (finish: boolean) => void) {
        this.closeCallback = callback;
        videoAds.preloadAds();
    }

    // 预加载一个视频广告. 启动游戏后应当尽早加载一个视频.
    public async preloadAds() {
        // 已经预加载了.
        // if (this.isPreloading) {
        //     return;
        // }
        // this.isPreloading = true;
        await this.createAds().then((ret) => {
            // this.isPreloading = !!ret;
        }).catch(() => {
            // this.isShowing = false;
            // this.isPreloading = false;
            this.hasError = true;
            if (this.closeCallback) {
                this.closeCallback(false);
                this.closeCallback = null;
            }
        });
    }

    /**
     * 展现广告banner. 可以设定一个延时展现的时长.为0立即展现.
     * @returns {Promise<>}
     */
    public async showAds() {
        if (!Wx.isWeChatEnv()) {
            console.error("非微信环境,不能添加广告");
            this.onVideoClose({isEnded: true});
            return;
        }
        // if (this.isShowing) {
        //     console.warn("广告已展现,不能重复展现.");
        //     return;
        // }
        // this.isShowing = true;
        await this.preloadAds();

        if (this.banner) {
            return this.banner.show();
        } else {
            return Promise.reject("banner 为空.");
        }
    }

    /**
     * 创建视频广告组件.并进行预加载.
     * @returns {Promise<>}
     */
    private createAds(): Promise<any> {
        if (!this.adUnitId) {
            console.error("未初始化视频广告ID,不能创建广告.");
            return Promise.reject();
        }
        return new Promise<any>((resolve) => {
            const sysInfo = wx.getSystemInfoSync();
            cc.log("系统信息:", sysInfo);
            if (sysInfo.SDKVersion < "2.0.4") {
                console.error("基础库版本<2.0.4, 无法显示广告.");
                resolve(null);
                return;
            }
            this.bannerCreateTime = Date.now();
            if (this.banner) {
                this.banner.offLoad(this.onVideoLoad);
                this.banner.offError(this.onError);
                this.banner.offClose(this.onVideoClose);
            }
            this.banner = wx.createRewardedVideoAd({
                adUnitId: this.adUnitId,
            });
            this.banner.onLoad(this.onVideoLoad);
            this.banner.onError(this.onError);
            this.banner.onClose(this.onVideoClose);
            resolve(this.banner);
        }).then((ret) => {
            if (ret) {
                return this.banner.load();
            } else {
                return Promise.resolve(false);
            }
        });
    }
}

export const videoAds: VideoAdsProvider = new VideoAdsProvider();